package com.up.selfshop.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @author liuzy
 * @since 2016年10月8日
 */
@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {
	@RequestMapping(value = "/form", method = RequestMethod.POST)
	@ResponseBody
	public String form(MultipartFile file) {
		String path = "D:/";
		File dir = new File(path);
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}
		try {
			String fileName = String.valueOf(System.currentTimeMillis());
			String ofileName = file.getOriginalFilename();
			if (ofileName.contains(".")) {
				fileName += ofileName.substring(ofileName.lastIndexOf("."));
			}
			File f = new File(path + fileName);
			file.transferTo(f);
			return f.getAbsolutePath();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "failed";
	}

	@RequestMapping(value = "/stream", method = RequestMethod.POST)
	@ResponseBody
	public String stream() {
		String path = "D:/";
		File dir = new File(path);
		if (!dir.isDirectory()) {
			dir.mkdirs();
		}
		try {
			String fileName = String.valueOf(System.currentTimeMillis());
			String ofileName = request.getParameter("fileName");
			if (ofileName.contains(".")) {
				fileName += ofileName.substring(ofileName.lastIndexOf("."));
			}
			File file = new File(path + fileName);
			BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			byte[] buf = new byte[1024];
			while (true) {
				int bytesIn = bis.read(buf, 0, 1024);
				if (bytesIn == -1) {
					break;
				} else {
					bos.write(buf, 0, bytesIn);
				}
			}
			bos.flush();
			bos.close();
			return file.getAbsolutePath();
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
}
